<template>
 <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :model="userDetail" :rules="rules" ref="infoRef" label-width="100px" style="width: 500px">
      <el-form-item label="登录名称">
        <el-input disabled v-model="userDetail.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userDetail.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userDetail.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交修改</el-button>
        <!-- 调用这个方法会清空表单 -->
        <!-- <el-button @click="$refs.infoRef.resetFields()">重置</el-button> -->
        <!-- 重置是还原成之前的昵称和邮箱 -->
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapState } from 'vuex'
import { reqUpdateUserInfo } from '@/api/user'
export default {
  name: 'UserInfo',
  computed: {
    ...mapState('user', ['userInfo']) // 虽然结构中双向绑定了数据,但是双向绑定的数据是基于vuex映射的一份新数据
    // userInfo () {
    //   return this.$store.state.user.userInfo
    // }
  },
  async mounted () {
    // this.userDetail = this.userInfo
    const res = await this.$store.dispatch('user/getUserInfo')
    this.userDetail = { ...res }
  },
  data () {
    return {
      userDetail: {},
      rules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: ['change', 'blur'] },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: ['change', 'blur'] }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: ['change', 'blur'] },
          { type: 'email', message: '邮箱格式不正确', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  methods: {
    // 重置
    reset () {
      this.userDetail = { ...this.userInfo }
    },
    // 更新资料
    handleSubmit () {
      // 0 -预校验
      this.$refs.infoRef.validate(async boo => {
        if (boo) {
          // 1. 发送请求
          const { data } = await reqUpdateUserInfo(this.userDetail)
          console.log(data)
          // 2. 提示
          this.$message.success(data.message)
          // 3. 重新获取个人信息更新视图
          this.$store.dispatch('user/getUserInfo')
        }
      })
    }
  }
}
</script>
